import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/index.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientBean;
import 'package:common_lib/repository/https.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorLoginBean;
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class AddPatientBloc extends BaseBloc {
  DoctorLoginBean.DoctorUser _userInfo;
  PatientBean.Datum _patientInfo = PatientBean.Datum();
  BehaviorSubject<PatientBean.Datum> dataSourceSubject = BehaviorSubject();

  @override
  void dispose() {
    dataSourceSubject?.close();
  }

  @override
  void initState() async {
    super.initState();
    var userInfo = await UserInfoCache.getInstance().get();
    _userInfo = userInfo;
  }

  // 操作：选择性别
  void selectedGender(context) async {
    var tempGender = await GenderPicker.showGenderPicker(
        context: context,
        selectedItem: GenderBean(
            Utils.returnGenderByInt(_patientInfo.sex), _patientInfo.sex));
    _patientInfo.sex = tempGender?.code ?? 0;
    dataSourceSubject.add(_patientInfo);
  }

  // 操作：选择日期
  void selectDate(context, birthDay) {
    showDatePicker(
            context: context,
            initialDate: DateUtil.getDateTime(birthDay) ?? new DateTime.now(),
            firstDate: new DateTime(1900, 1, 1),
            lastDate: new DateTime.now())
        .then((value) {
      _patientInfo.birthDay =
          DateUtil.formatDate(value, format: DateFormats.y_mo_d);
      dataSourceSubject.add(_patientInfo);
    });
  }

  // 操作：选择地址
  void selectAddress(context) async {
    AddressResult result = await AddressPicker.showAddressPicker(
        context: context,
        locationCode: _patientInfo?.areaCode ?? _patientInfo.cityCode);
    _patientInfo.province = result.provinceName;
    _patientInfo.provinceCode = result.provinceId;
    _patientInfo.city = result.cityName;
    _patientInfo.cityCode = result.cityId;
    _patientInfo.area = result.areaName;
    _patientInfo.areaCode = result.areaId;
    dataSourceSubject.add(_patientInfo);
  }

  String spliceAddress() {
    String provinceName = _patientInfo?.province ?? "";
    String cityName = _patientInfo?.city ?? "";
    String areaName = _patientInfo?.area ?? "";
    return provinceName + cityName + areaName;
  }

  // 操作：编辑病种
  void editSickness(SicknessResult result) {
    _patientInfo?.historyOfAllergy = result.historyOfAllergy;
    _patientInfo?.allergyDetail = result.allergyDetail;
    _patientInfo?.historyOfSickness = result.historyOfSickness;
    _patientInfo?.sicknessDetail = result.sicknessDetail;
    _patientInfo?.liver = result.liver;
    _patientInfo?.renal = result.renal;
    _patientInfo?.pregnancy = result.pregnancy;
  }

  // 构建病种
  SicknessResult buildSickness() {
    return SicknessResult(
        _patientInfo?.historyOfAllergy ?? "无",
        _patientInfo?.allergyDetail ?? "",
        _patientInfo?.historyOfSickness ?? "无",
        _patientInfo?.sicknessDetail ?? "",
        _patientInfo?.liver ?? '正常',
        _patientInfo?.renal ?? '正常',
        _patientInfo?.pregnancy ?? '否');
  }

  // 操作：初始化数据
  void initialDatas({PatientBean.Datum patientInfo, bool isEdit}) {
    // 性别初始化
    _patientInfo.sex = 1;
    // 出生日期初始化
    _patientInfo.birthDay =
        DateUtil.formatDate(DateTime.now(), format: DateFormats.y_mo_d);
    // 病种初始化
    _patientInfo.historyOfAllergy = "无";
    _patientInfo.allergyDetail = "";
    _patientInfo.historyOfSickness = "无";
    _patientInfo.sicknessDetail = "";
    _patientInfo.liver = "正常";
    _patientInfo.renal = "正常";
    _patientInfo.pregnancy = "否";

    _patientInfo = patientInfo;
    dataSourceSubject.add(_patientInfo);
  }

  // 操作：编辑姓名
  void editPatientName(value) {
    _patientInfo.patientName = value;
  }

  // 操作：编辑电话
  void editPhone(value) {
    _patientInfo.phone = value;
  }

  // 操作：身份证
  void editIdCard(value) {
    _patientInfo.patientIdNumber = value;
  }

  // 操作：删除患者
  void deletePatient(context) {
    // print("删除该患者");
    // Custom_iOS_Dialog.prompt(context, content: "您确定要删除该患者吗？", okFn: () {
    //   print("删除该患者1");
    _deletePatientInfoFun(context);
    // }, cancelFn: () {});
  }

  // 操作: 编辑详细地址
  void editDetailAddress(value) {
    _patientInfo.address = value;
  }

  // 跳转---编辑患者
  void savePatientInfo(BuildContext context, bool isEdit) {
    if (ObjectUtil.isEmpty(_userInfo.keyID)) {
      ToastUtil.warning("获取当前登录用户信息失败，请重新登录");
      return;
    }
    if (ObjectUtil.isEmpty(_patientInfo.patientName)) {
      ToastUtil.warning("请输入患者姓名");
      return;
    }
    if (_patientInfo.sex != 1 && _patientInfo.sex != 2) {
      ToastUtil.warning("请选择患者性别");
      return;
    }
    if (ObjectUtil.isEmpty(_patientInfo.phone)) {
      ToastUtil.warning("请输入手机号");
      return;
    }
    if (!RegexUtil.isMobileExact(_patientInfo.phone)) {
      ToastUtil.warning("请输入正确的手机号");
      return;
    }
    if (ObjectUtil.isEmpty(_patientInfo.patientIdNumber)) {
      ToastUtil.warning('请输入身份证号');
      return;
    }

    if (!RegexUtil.isIDCard(_patientInfo.patientIdNumber)) {
      ToastUtil.warning('请输入合法身份证号');
      return;
    }

    if (_patientInfo.birthDay == null) {
      ToastUtil.warning('请选择出生日期');
      return;
    }

    if (ObjectUtil.isEmpty(_patientInfo.province) ||
        ObjectUtil.isEmpty(_patientInfo.city)) {
      ToastUtil.warning('请选择地址');
      return;
    }

    if (ObjectUtil.isEmpty(_patientInfo.address)) {
      ToastUtil.warning('请输入详细地址');
      return;
    }

    if (isEdit) {
      _updatePatientInfoFun(context);
    } else {
      _savePatientInfoFun(context);
    }
  }

  // 网路请求：保存患者信息
  void _savePatientInfoFun(BuildContext context) async {
    _patientInfo.doctorId = _userInfo.keyID;
    _patientInfo.latitude = "30.53972816467285";
    _patientInfo.longitude = "104.05217742919922";
    var result = await CommonHttp.savePatientInfo(_patientInfo.toJson());
    if (result.isSuccess) {
      Routers.pop(context, "refresh");
    } else {
      ResultBody error = result;
      ToastUtil.error(error.error.msg);
    }
  }

  // 网路请求：更新患者信息
  void _updatePatientInfoFun(context) async {
    var result = await CommonHttp.updatePatientInfo(_patientInfo.toJson());
    if (result.isSuccess) {
      Routers.pop(context, "refresh");
    } else {
      ResultBody error = result;
      ToastUtil.error(error.error.msg);
    }
  }

  // 网路请求：删除患者
  void _deletePatientInfoFun(BuildContext context) async {
    var result = await CommonHttp.deletePatientInfo(
        {"id": _patientInfo.keyId, "doctorID": _patientInfo.doctorId});
    if (result.isSuccess) {
      Routers.pop(context, "refresh");
    } else {
      ResultBody error = result;
      ToastUtil.error(error.error.msg);
    }
  }
}
